<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本名称" prop="versionName">
        <el-input
          v-model="queryParams.versionName"
          placeholder="请输入版本名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学段" prop="period">
        <el-select
          v-model="queryParams.period"
          placeholder="请选择学段"
          clearable
          style="width: 240px"
        >
          <el-option label="小学" value="小学" />
          <el-option label="初中" value="初中" />
          <el-option label="高中" value="高中" />
          <el-option label="大学" value="大学" />
        </el-select>
      </el-form-item>
      <el-form-item label="语言分类" prop="languageCategory">
        <el-select
          v-model="queryParams.languageCategory"
          placeholder="语言分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="lang in languageOptions"
            :key="lang.id"
            :label="lang.name"
            :value="lang.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:exam:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['module:exam:paper:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:exam:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:exam:paper:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷ID" align="center" prop="id" width="100" />
      <el-table-column label="版本名称" align="center" prop="versionName" :show-overflow-tooltip="true" />
      <el-table-column label="学段" align="center" prop="period" width="100" />
      <el-table-column label="语言" align="center" prop="language" width="100" />
      <el-table-column label="语言分类" align="center" prop="languageCategory" width="120" />
      <el-table-column label="试题总数" align="center" prop="totalQuestions" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:exam:paper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:exam:paper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="版本ID" prop="versionId">
          <el-input-number v-model="form.versionId" :min="0" placeholder="请输入版本ID" style="width: 100%" />
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="学段" prop="period">
          <el-select v-model="form.period" placeholder="请选择学段" style="width: 100%">
            <el-option label="小学" value="小学" />
            <el-option label="初中" value="初中" />
            <el-option label="高中" value="高中" />
            <el-option label="大学" value="大学" />
          </el-select>
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="form.language" placeholder="请输入语言（如：英语、日语等）" />
        </el-form-item>
        <el-form-item label="语言分类" prop="languageCategory">
          <el-select v-model="form.languageCategory" placeholder="请选择语言分类" style="width: 100%">
            <el-option
              v-for="lang in languageOptions"
              :key="lang.id"
              :label="lang.name"
              :value="lang.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试题总数" prop="totalQuestions" v-if="isEdit">
          <el-input-number v-model="form.totalQuestions" controls-position="right" :min="0" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="参考词典" prop="referenceDicts">
          <el-select
            v-model="form.referenceDicts"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入参考词典"
            style="width: 100%"
          >
            <el-option
              v-for="dict in dictBookOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入试卷对话框 -->
    <el-dialog title="导入试卷" :visible.sync="importOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="importForm" :model="importForm" label-width="120px">
        <el-form-item label="JSON文件" prop="file">
          <el-upload
            ref="fileUpload"
            class="upload-demo"
            drag
            :limit="1"
            accept=".json"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            action="#"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将JSON文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <p style="margin: 5px 0; color: #606266;">
                <i class="el-icon-info"></i> 支持格式：JSON文件
              </p>
              <p style="margin: 5px 0; color: #909399; font-size: 12px;">
                JSON格式示例：<br/>
                {<br/>
                &nbsp;&nbsp;"version": {<br/>
                &nbsp;&nbsp;&nbsp;&nbsp;"id": 68,<br/>
                &nbsp;&nbsp;&nbsp;&nbsp;"versionName": "小升初分类词汇",<br/>
                &nbsp;&nbsp;&nbsp;&nbsp;"period": "小学"<br/>
                &nbsp;&nbsp;},<br/>
                &nbsp;&nbsp;"rawData": { ... }<br/>
                }
              </p>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="importForm.language" placeholder="请输入语言（如：英语、日语等）" />
        </el-form-item>
        <el-form-item label="语言分类" prop="languageCategory">
          <el-select v-model="importForm.languageCategory" placeholder="请选择语言分类" style="width: 100%">
            <el-option
              v-for="lang in languageOptions"
              :key="lang.id"
              :label="lang.name"
              :value="lang.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport">确 定</el-button>
        <el-button @click="importOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExamPaper, getExamPaper, delExamPaper, addExamPaper, updateExamPaper, importExamPaper } from "@/api/module/exam";
import { getAllLanguageCategory, listDictBook } from "@/api/module/dict";

export default {
  name: "ExamPaper",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      paperList: [],
      // 语言分类选项
      languageOptions: [],
      // 词典选项
      dictBookOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否是编辑模式
      isEdit: false,
      // 导入对话框
      importOpen: false,
      // 导入文件列表
      fileList: [],
      // 导入表单
      importForm: {
        language: undefined,
        languageCategory: undefined
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionName: undefined,
        period: undefined,
        languageCategory: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        versionName: [
          { required: true, message: "版本名称不能为空", trigger: "blur" }
        ],
        period: [
          { required: true, message: "学段不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getLanguageOptions();
    this.getDictBookOptions();
  },
  methods: {
    /** 查询试卷列表 */
    getList() {
      this.loading = true;
      listExamPaper(this.queryParams).then(response => {
        this.paperList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('查询试卷列表失败：', error);
        this.paperList = [];
        this.total = 0;
        this.loading = false;
        // 如果是404错误，提示用户可能是接口不存在或数据库表未创建
        if (error.response && error.response.status === 404) {
          this.$modal.msgError('接口不存在，请检查后端服务是否正常启动，或数据库表是否已创建');
        } else if (error.message && error.message.includes('404')) {
          this.$modal.msgError('接口不存在，请检查后端服务是否正常启动，或数据库表是否已创建');
        } else {
          this.$modal.msgError('查询试卷列表失败：' + (error.msg || error.message || '未知错误'));
        }
      });
    },
    /** 获取语言分类选项 */
    getLanguageOptions() {
      getAllLanguageCategory().then(response => {
        this.languageOptions = response.data;
      });
    },
    /** 获取词典选项 */
    getDictBookOptions() {
      listDictBook({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.dictBookOptions = response.rows || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        versionId: undefined,
        versionName: undefined,
        period: undefined,
        language: undefined,
        languageCategory: undefined,
        totalQuestions: 0,
        referenceDicts: [],
        status: "0",
        remark: undefined
      };
      this.isEdit = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.open = true;
      this.title = "添加试卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids[0]
      getExamPaper(id).then(response => {
        this.form = response.data;
        // 确保referenceDicts是数组类型
        if (!Array.isArray(this.form.referenceDicts)) {
          this.form.referenceDicts = [];
        }
        this.open = true;
        this.title = "修改试卷";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateExamPaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除试卷编号为"' + ids + '"的数据项？').then(function() {
        return delExamPaper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importOpen = true;
      this.fileList = [];
      this.importForm = {
        language: undefined,
        languageCategory: undefined
      };
    },
    /** 处理文件上传 */
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    /** 移除文件 */
    handleFileRemove() {
      this.fileList = [];
    },
    /** 提交导入 */
    submitImport() {
      if (this.fileList.length === 0) {
        this.$modal.msgWarning("请选择要导入的JSON文件");
        return;
      }
      
      const loading = this.$loading({
        lock: true,
        text: '正在上传并导入试卷数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 创建FormData
      const formData = new FormData();
      
      // 添加文件
      const file = this.fileList[0].raw;
      formData.append('file', file);
      
      // 添加语言信息
      if (this.importForm.language) {
        formData.append('language', this.importForm.language);
      }
      if (this.importForm.languageCategory) {
        formData.append('languageCategory', this.importForm.languageCategory);
      }
      
      // 调用导入API
      importExamPaper(formData).then(response => {
        loading.close();
        this.$modal.msgSuccess(response.msg || '试卷导入成功');
        this.importOpen = false;
        this.getList();
      }).catch(error => {
        loading.close();
        console.error('导入失败：', error);
        this.$modal.msgError('试卷导入失败：' + (error.msg || error.message || '未知错误'));
      });
    }
  }
};
</script>

